import React, { useState } from 'react';
import { Button, message } from 'antd';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { EditOutlined } from '@ant-design/icons';
import { updateUserPassword } from '@/services/api/user';

const handleEditPassword = async (user_id: number, fields: API.UserUpdatePasswordDto) => {
  const hide = message.loading('正在添加');
  try {
    const { status_code, message: msg } = await updateUserPassword({ user_id }, { ...fields });
    if (status_code === 200) {
      hide();
      message.success(msg);
      return true;
    }
    message.error(msg);
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

type EditUserPasswordViewProps = {
  user_id: number;
  onSubmit: () => void;
};

const EditUserPassword: React.FC<EditUserPasswordViewProps> = (props) => {
  const { user_id, onSubmit } = props;
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  return (
    <>
      {' '}
      <Button
        type="primary"
        key="primary"
        onClick={() => {
          handleModalVisible(true);
        }}
      >
        <EditOutlined /> 修改密码
      </Button>
      <ModalForm
        isKeyPressSubmit={false}
        title={'修改密码'}
        width="400px"
        open={modalVisible}
        onOpenChange={() => {
          handleModalVisible(false);
        }}
        onFinish={async (value) => {
          const success = await handleEditPassword(user_id, value as API.UserUpdatePasswordDto);
          if (success) {
            onSubmit();
            handleModalVisible(false);
          }
        }}
      >
        <ProFormText.Password
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: '密码为必填项',
            },
          ]}
        />
      </ModalForm>
    </>
  );
};
export default EditUserPassword;
